using FastDevTemplate.Api;
using FastDevTemplate.Api.Filter;
using FastDevTemplate.Api.Middlewares;
using FastDevTemplate.Service;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("appsettings.json", true);
// Add services to the container.
builder.Services
.AddControllers(options => { options.Filters.Add(typeof(ApiPermissionVerificationFilter)); })
.ConfigureApiBehaviorOptions(opt => { opt.SuppressModelStateInvalidFilter = true; })
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    options.JsonSerializerOptions.PropertyNamingPolicy = new UpperCaseNamingPolicy(); // 全小写
});

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
        });
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Token", new OpenApiSecurityScheme
    {
        Description = "请输入token",
        Name = "token",
        In = ParameterLocation.Header,
        Scheme = "token"
    });

    options.AddSecurityDefinition("UUID", new OpenApiSecurityScheme
    {
        Description = "请输入uuid",
        Name = "uuid",
        In = ParameterLocation.Header,
        Scheme = "uuid"
    });

    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Token" }
            },
            new string[] { }
        }
    });

    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "UUID" }
            },
            new string[] { }
        }
    });

    options.SwaggerDoc("v1", new OpenApiInfo { Title = "FastDevTemplate API", Version = "v1" });
});

builder.Services.AddFastDevTemplateService();

builder.Services.LoadPermissions();
builder.Services.LoadDefaultRoles();
builder.Services.LoadDefaultUsers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
// app.UseLogRecord();
app.UseHttpsRedirection();
app.UseCors("AllowSpecificOrigin");
app.MapControllers();
app.Run();